package com.ffmpeg.util.infra.util;

import java.util.function.ToDoubleFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ffmpeg.util.infra.constant.FileConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author :meng.wang10@hand-china.com 2024-01-29 19:13:00
 * @description :
 */
public class ComparatorUtil {

    private final static Logger logger = LoggerFactory.getLogger(ComparatorUtil.class);

    public static class ChangeToDouble implements ToDoubleFunction<String> {
        @Override
        public double applyAsDouble(String value) {
            return applyAsDouble(value, null, null);
        }

        /**
         * 将字符串转换为double类型的值
         *
         * @param value  字符串
         * @param prefix 前缀
         * @param suffix 后缀
         * @return double值
         */
        public static double applyAsDouble(String value, String prefix, String suffix) {
            if (StringUtils.isEmpty(value)) {
                logger.debug("value is empty");
                return FileConstant.Number.ZERO;
            }
            if (StringUtils.isNotEmpty(prefix)) {
                value = StringUtils.remove(value, prefix);
            }
            if (StringUtils.isNotEmpty(suffix)) {
                value = StringUtils.removeEnd(value, suffix);
            }
            Pattern pattern = Pattern.compile(FileConstant.Matches.MATCH_NUMBER);
            Matcher matcher = pattern.matcher(value);
            StringBuilder stringBuffer = new StringBuilder();
            while (matcher.find()) {
                stringBuffer.append(matcher.group());
            }
            return NumberUtils.toDouble(stringBuffer.toString(), FileConstant.Number.ZERO);
        }
    }
}
